﻿(function () {
    "use strict";

    var feeds = [
            // fixed json
            // key: Group key
            //{ query: new Queries.JsonQuery('group1') },

            // search in twitter
            // key: Group key
            // q: search query (https://dev.twitter.com/docs/using-search)
            // title:
            // subtitle:
            // description:
            //{ query: new Queries.TwitterQuery('group2', 'windows 8', 'Se dice de Windows 8', "lo que se dice de Windows 8 en twitter", "A días del lanzamiento oficial las personas opinan de windows 8") },

            // rss version 2.0
            // key: Group key
            // url:
            // logoUrl:
            { query: new Queries.FeedQuery('group3', 'http://alt1040.com/feed', 'http://hipertextual.com/_/v6/img/alt/logo.png') },

            // atom
            // key: Group key
            // url:
            // logoUrl:
            //{ query: new Queries.FeedQuery('group4', 'http://blogs.msdn.com/b/b8/atom.aspx', 'http://res1.windows.microsoft.com/resbox/es/6.2/2012-Win8GA/08670568-c1f4-4386-9ebc-95378384f31e_5.png') },

            // flickr
            // title:
            // subtitle:
            // description:
            // apiKey: api key (see flickr documentation)
            // photosetId: photo set id (see flickr documentation)
            //{ query: new Queries.FlickrPhotosetsGetPhotosQuery('group5', 'Flickr', 'Mi album en Flickr', "lo que hicimos en la escuela", "44dd67100b03e7d4e2eee2a6d1cd99e6", "72157631793541656") },
   ];

    var blogPosts = new WinJS.Binding.List();
    var groupedItems = blogPosts.createGrouped(
        function groupKeySelector(item) { return item.group.key; },
        function groupDataSelector(item) { return item.group; }
    );

    var localFolder = Windows.Storage.ApplicationData.current.localFolder;

    function getFeeds() {
        var dataPromises = [];

        // Get the content for each feed and get items from xml.
        feeds.forEach(function (feed) {
            // We bind the data promise to the feed, to update the feed later with its response
            feed.dataPromise = feed.query.getFeed();
            dataPromises.push(feed.dataPromise);
        });

        return WinJS.Promise.join(dataPromises).then(function () { return feeds; }) // We return the feeds instead of the promise, for signature consistency
    };

    function isInternetAvailable() {
        var internetProfile = Windows.Networking.Connectivity.NetworkInformation.getInternetConnectionProfile();
        return internetProfile != null && internetProfile.getNetworkConnectivityLevel() == Windows.Networking.Connectivity.NetworkConnectivityLevel.internetAccess;
    }

    function getBlogPosts() {
        if (isInternetAvailable()) {
            var pr = document.createElement("progress");
            var header = document.querySelector("header h1");
            header.appendChild(pr);

            return getFeeds()
                .then(function (feeds) {
                    feeds.forEach(function (feed) {
                        feed.dataPromise.then(function (articles) {
                            articles.forEach(function (article) {
                                // Avoid duplication if the user refreshes the data
                                if (resolveItemReference([article.group.key, article.title]) == undefined) {
                                    // Store the post info we care about in the array.
                                    blogPosts.push(article);
                                }
                            })
                        });
                        
                    });
                    writeFile(JSON.stringify(blogPosts));
                })
                .then(function (feeds) {
                    header.removeChild(pr);
                    return feeds;
                });
        } else {
            readFile();
            ShowConnectionError();
        }
    };

    function ShowConnectionError() {
        var popup = Windows.UI.Popups.MessageDialog("Ha habido un error intentando acceder a los nuevos datos o no hay conexiones de red disponibles.\nPor favor asegúrese de contar con acceso de red y vuelva a abrir la aplicación.", "Sin conexión");
        popup.showAsync();
    }

    function writeFile(content) {
        localFolder.createFileAsync("dataFile.txt", Windows.Storage.CreationCollisionOption.replaceExisting)
           .then(function (dataFile) {
               return Windows.Storage.FileIO.writeTextAsync(dataFile, content);
           });
    }

    function readFile() {
        localFolder.getFileAsync("dataFile.txt")
           .then(function (sampleFile) {
               return Windows.Storage.FileIO.readTextAsync(sampleFile);
           }).done(function (content) {
               var bp = JSON.parse(content);
               while (blogPosts.length > 0) {
                   blogPosts.pop();
               }

               for (var i = 1; i <= bp._lastNotifyLength; i++) {
                   var p = bp._keyMap[i];
                   blogPosts.push({
                       group: p.data.group, key: p.data.key, title: p.data.title,
                       author: p.data.author, pubDate: p.data.pubDate, backgroundImage: p.data.backgroundImage,
                       content: p.data.content
                   });
               }
           }, function () {
           });
    }

    WinJS.Namespace.define("Data", {
        items: groupedItems,
        groups: groupedItems.groups,
        getItemReference: getItemReference,
        getItemsFromGroup: getItemsFromGroup,
        resolveGroupReference: resolveGroupReference,
        resolveItemReference: resolveItemReference,
        refresh: getBlogPosts
    });

    // Get a reference for an item, using the group key and item title as a
    // unique reference to the item that can be easily serialized.
    function getItemReference(item) {
        return [item.group.key, item.title];
    }

    // This function returns a WinJS.Binding.List containing only the items
    // that belong to the provided group.
    function getItemsFromGroup(group) {
        return blogPosts.createFiltered(function (item) { return item.group.key === group.key; });
    }

    // Get the unique group corresponding to the provided group key.
    function resolveGroupReference(key) {
        for (var i = 0; i < groupedItems.groups.length; i++) {
            if (groupedItems.groups.getAt(i).key === key) {
                return groupedItems.groups.getAt(i);
            }
        }
    }

    // Get a unique item from the provided string array, which should contain a
    // group key and an item title.
    function resolveItemReference(reference) {
        for (var i = 0; i < groupedItems.length; i++) {
            var item = groupedItems.getAt(i);
            if (item.group.key === reference[0] && item.title === reference[1]) {
                return item;
            }
        }
    }

})();
